package com.token.iot.bratterycharging.gateway.server;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.outstanding.framework.core.Logger;
import com.outstanding.framework.log.LoggerFactory;
import com.token.iot.bratterycharging.gateway.ChannelHandlerContextManager;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;

@Component("heartBeat")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class HeartBeat extends ChannelHandlerAdapter {
	
	
	private static ChannelHandlerContextManager manager = new ChannelHandlerContextManager();
	static public final AttributeKey<String> attributeIMEI = AttributeKey.valueOf("IMEI");
	private static Logger loger = LoggerFactory.getLogger(HeartBeat.class);

	
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent e = (IdleStateEvent) evt;
			if (e.state() == IdleState.READER_IDLE) {
				ctx.channel().attr(attributeIMEI);
				Attribute<String> attr = ctx.channel().attr(attributeIMEI);
				String id = "";
				if (attr.get() != null && !StringUtils.isEmpty(attr.get())) {
					id = attr.get();
				}
				loger.debug("ping timeout,remove imei:" + id);
				
				// 关闭通道
				ctx.close();
				

			} else if (e.state() == IdleState.WRITER_IDLE) {
				
			}
		}
	}
}
